package com.jt.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jt.mapper.itemDescMapper;
import com.jt.mapper.itemMapper;
import com.jt.pojo.Item;
import com.jt.pojo.ItemDesc;
import com.jt.vo.ImageVo;
import com.jt.vo.ItemVO;
import com.jt.vo.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service
public class itemServiceImpl implements itemService {
    @Autowired
    private itemMapper itemMapper;

    @Autowired
    private itemDescMapper itemDescMapper;

    @Value("${file.localDir}")
    private String localDirPath;

    @Value("${file.urlPath}")
    private String preURLPath;

    /**
     * 1.验证上传的文件是图片!  jpg|png|gif 采用正则的方式校验
     * 2.防止恶意程序攻击,  验证图片是否有宽度和高度.
     * 3.文件分目录存储     例如: /2021/11/11
     * 例如2: hash码 8位hash xx/xx/xx/xx
     * 数据hahs时 特征:因为是算法 可能造成数据分配不均!!!
     * 4.防止文件重名,修改文件名称 UUID
     *
     * @param file
     * @return
     */
    @Override
    public ImageVo upload(MultipartFile file) {
        //1.校验图片类型是否正确   正则表达式 a.jpg
        //1.1 获取文件名称
        String fileName = file.getOriginalFilename();
        //1.3将名称全部小写
        fileName = fileName.toLowerCase();
        //1.2 正则校验  bug!!!!
        if(!fileName.matches("^.+\\.(jpg|png|gif)$")){
            //如果文件不是图片 则返回null
            return null;
        }
        //2.判断是否为恶意程序
        //2.1 通过图片对象 获取宽度和高度
        try {
            BufferedImage bufferedImage = ImageIO.read(file.getInputStream());
            int height = bufferedImage.getHeight();
            int width = bufferedImage.getWidth();
            if(height==0 || width==0){
                return null;
            }

            //3实现分目录存储
            //3.1 按照时间将分配目录  /yyyy/MM/dd/
            String dateDirPath = new SimpleDateFormat("/yyyy/MM/dd/")
                    .format(new Date());
            //3.2 "D:/images/yyyy/MM/dd/
            String localDir = localDirPath + dateDirPath;
            File dirFile = new File(localDir);
            if(!dirFile.exists()){//如果目录不存在,则创建目录
                dirFile.mkdirs();
            }

            //4. 防止文件重名  生成UUID.文件类型
            String uuid = UUID.randomUUID().toString()
                    .replace("-","");
            int index = fileName.lastIndexOf(".");
            //获取后缀   .jpg   abc.jpg
            String fileType = fileName.substring(index); //从给定的位置开始 向后截取数据
            String realFileName = uuid + fileType;
            //5.实现文件上传
            // 5.1 拼接文件全路径 目录/文件名称
            String localFilePath = localDir + realFileName;
            // 5.2 完成文件上传
            file.transferTo(new File(localFilePath));

            /**封装返回值.
             * 不带磁盘的本地存储路径 虚拟动态目录
             * D:\images\2021\07\13\8b7b3ef3c88845a6876371b4815244ca.jpg
             */
            String virtualPath = dateDirPath + realFileName;
            //动态拼接网络访问地址
            //图片访问网络地址: http://image.jt.com(域名)/2021/07/13/85a.jpg(动态路径)
            //真实的磁盘地址:    D:/images/2021/07/13/85a.jpg
            String urlPath = preURLPath + virtualPath;
            ImageVo imageVO = new ImageVo(virtualPath,urlPath,realFileName);
            System.out.println(imageVO);
            return imageVO;
        } catch (IOException e) {
            e.printStackTrace();
            //终止程序
            return null;
        }
    }

    @Override
    @Transactional
    public void saveItem(ItemVO itemVO) {
        Item item = itemVO.getItem();
        itemMapper.insert(item.setStatus(true));
        ItemDesc itemDesc = itemVO.getItemDesc();

        itemDesc.setId(item.getId());
        itemDescMapper.insert(itemDesc);
    }

    @Override
    @Transactional
    public void updateItem(Item item) {
        itemMapper.updateById(item);
    }

    @Override
    public Item selectById(Integer id) {
        return itemMapper.selectById(id);
    }

    @Override
    @Transactional
    public void deleteById(Integer id) {
        itemMapper.deleteById(id);
        itemDescMapper.deleteById(id);
    }

    @Override
    @Transactional
    public void updateStatus(Item item) {
        itemMapper.updateById(item);
    }

    @Override
    public PageResult getItemList(PageResult pageResult) {
        IPage<Item> page = new Page<>(pageResult.getPageNum(), pageResult.getPageSize());
        QueryWrapper<Item> queryWrapper = new QueryWrapper<>();
        boolean flag = StringUtils.hasLength(pageResult.getQuery());
        queryWrapper.like(flag, "title", pageResult.getQuery());

        IPage<Item> itemIPage = itemMapper.selectPage(page, queryWrapper);
        long total = itemIPage.getTotal();
        List<Item> records = itemIPage.getRecords();
        return pageResult.setRows(records).setTotal(total);
    }
}
